<script setup>
import { ref, reactive, onMounted } from 'vue'
//导入发送请求的axios对象
import request from "../utils/request"
import {useRouter} from 'vue-router'
const router=useRouter()

let registUser=reactive({
  username:"",
  userPwd:"",
  phone:"",
  verificationCode:"",
  securityQuestions: []
})

let usernameMsg=ref('')
let userPwdMsg=ref('')
let confirmPwdMsg=ref('')
let confirmPwd=ref('')
let phoneMsg=ref('')
let verificationCodeMsg=ref('')
let securityQuestionsMsg=ref('')

// 验证码相关状态
let generatingCode=ref(false)
let countdown=ref(0)
let codeGenerated=ref(false)

// 预设安全问题
const securityQuestions = [
  { id: 1, question: "你的小学名称是什么？" },
  { id: 2, question: "你的第一个宠物叫什么名字？" },
  { id: 3, question: "你最喜欢的颜色是什么？" },
  { id: 4, question: "你的出生地是哪里？" },
  { id: 5, question: "你最喜欢的食物是什么？" },
  { id: 6, question: "你最喜欢的电影是什么？" },
  { id: 7, question: "你最喜欢的运动是什么？" },
  { id: 8, question: "你的理想职业是什么？" },
  { id: 9, question: "你最喜欢的季节是什么？" },
  { id: 10, question: "你最喜欢的城市是哪里？" }
]

// 用户选择的安全问题和答案
const selectedQuestions = reactive({})

async function checkUsername(){
  var reg=/^[\u4e00-\u9fa5a-zA-Z0-9_]{2,16}$/;
  var username=registUser.username;
  if(!reg.test(username)){
    usernameMsg.value="用户名格式有误（2-16位，支持中文、字母、数字、下划线）";
    return false;
  }
  //格式正确，通过之后，继续校验用户名是否被占用
  try {
    const {data} = await request.get(`/user/checkUsername?username=${username}`);
    if (data.code==200){
      // 用户名可用
      usernameMsg.value="可用";
      return true;
    }else if (data.code==505){
      // 用户名已被使用，不可用
      usernameMsg.value="不可用";
      return false;
    }else {
      // 其他错误
      usernameMsg.value="检查失败，请重试";
      return false;
    }
  } catch (error) {
    console.error('检查用户名失败:', error);
    usernameMsg.value="检查失败，请重试";
    return false;
  }
}

function checkUserPwd(){
  var reg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
  var userPwd=registUser.userPwd;
  if(!reg.test(userPwd)){
    userPwdMsg.value="密码格式有误（8-20位，必须包含大小写字母、数字、特殊字符）";
    return false;
  }
  userPwdMsg.value="密码格式正确";
  return true;
}

function checkConfirmPwd(){
  var reg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
  var userPwd=registUser.userPwd;
  var confirmPwdValue=confirmPwd.value;

  if(!reg.test(confirmPwdValue)){
    confirmPwdMsg.value="密码格式有误（8-20位，必须包含大小写字母、数字、特殊字符）";
    return false;
  }else if(userPwd !== confirmPwdValue){
    confirmPwdMsg.value="两次密码不一致";
    return false;
  }
  confirmPwdMsg.value="密码一致";
  return true;
}

function checkPhone(){
  var reg=/^1[3-9]\d{9}$/;
  var phone=registUser.phone;
  if(!phone){
    phoneMsg.value="请输入手机号";
    return false;
  }
  if(!reg.test(phone)){
    phoneMsg.value="手机号格式不正确";
    return false;
  }
  phoneMsg.value="手机号格式正确";
  return true;
}

function checkVerificationCode(){
  var reg=/^\d{5}$/;
  var code=registUser.verificationCode;
  if(!code){
    verificationCodeMsg.value="请输入验证码";
    return false;
  }
  if(!reg.test(code)){
    verificationCodeMsg.value="请输入5位数字验证码";
    return false;
  }
  verificationCodeMsg.value="验证码格式正确";
  return true;
}

function checkSecurityQuestions(){
  const selectedCount = Object.keys(selectedQuestions).length;
  if(selectedCount < 3){
    securityQuestionsMsg.value="请至少选择3个安全问题并填写答案";
    return false;
  }
  
  // 检查是否所有选中的问题都有答案
  for(const questionId in selectedQuestions){
    if(!selectedQuestions[questionId].answer || selectedQuestions[questionId].answer.trim() === ''){
      securityQuestionsMsg.value="请为所有选中的安全问题填写答案";
      return false;
    }
  }
  
  securityQuestionsMsg.value="安全问题设置完成";
  return true;
}

// 生成验证码
async function generateCode(){
  if(!checkPhone() || generatingCode.value || countdown.value > 0){
    return;
  }
  
  generatingCode.value = true;
  try {
    const {data} = await request.post("/api/auth/generate-code", {
      phone: registUser.phone
    });
    
    if(data.code === 200){
      // 开始倒计时
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if(countdown.value <= 0){
          clearInterval(timer);
        }
      }, 1000);
      
      codeGenerated.value = true;
      alert("验证码已生成，请联系管理员获取");
    } else {
      alert(data.message || "生成失败");
    }
  } catch (error) {
    console.error('生成验证码失败:', error);
    alert("生成失败，请重试");
  } finally {
    generatingCode.value = false;
  }
}

function toggleQuestion(questionId){
  if(selectedQuestions[questionId]){
    // 取消选择
    delete selectedQuestions[questionId];
  } else {
    // 选择问题
    selectedQuestions[questionId] = { answer: '' };
  }
  checkSecurityQuestions();
}

async function checkForm(){
  var f1=checkUserPwd();
  var f2=await checkUsername();
  var f3=checkConfirmPwd();
  var f4=checkPhone();
  var f5=checkVerificationCode();
  var f6=checkSecurityQuestions();
  return f1&&f2&&f3&&f4&&f5&&f6;
}

//注册的方法
async function regist(){
  //校验所有输入框是否合法
  if(!(await checkForm())){
    return
  }
  
  try {
    // 第一步：带验证码的注册
    const registData = {
      username: registUser.username,
      userPwd: registUser.userPwd,
      phone: registUser.phone,
      verificationCode: registUser.verificationCode
    }
    
    let {data} = await request.post("/user/registWithCode", registData)
    if(data.code==200){
      // 注册成功，继续设置安全问题
      await setSecurityQuestions()
    }else{
      //注册失败跳转到失败页面
      router.push("/registFail")
    }
  } catch (error) {
    console.error('注册失败:', error);
    router.push("/registFail")
  }
}

// 设置安全问题
async function setSecurityQuestions(){
  try {
    const securityData = {
      username: registUser.username,
      securityQuestions: Object.keys(selectedQuestions).map(questionId => ({
        questionId: parseInt(questionId),
        answer: selectedQuestions[questionId].answer
      }))
    }
    
    let {data} = await request.post("/user/setSecurityAnswers", securityData)
    if(data.code==200){
      // 安全问题设置成功，跳转到成功页面
      router.push("/registSuccess")
    }else{
      // 安全问题设置失败，但注册已成功，跳转到成功页面并提示
      console.warn('安全问题设置失败，但注册已成功:', data.message)
      router.push("/registSuccess")
    }
  } catch (error) {
    console.error('安全问题设置失败:', error);
    // 安全问题设置失败，但注册已成功，跳转到成功页面
    router.push("/registSuccess")
  }
}

// 初始化particlesJS
function initParticles() {
  if (typeof particlesJS !== 'undefined') {
    particlesJS("particles-bg", {
      "particles": {
        "number": { "value": 40, "density": { "enable": true, "value_area": 800 } },
        "color": { "value": "#ffffff" },
        "shape": { "type": "circle" },
        "opacity": { "value": 0.7, "random": true },
        "size": { "value": 8, "random": true },
        "move": {
          "enable": true,
          "speed": 1.5,
          "direction": "top",
          "straight": false,
          "out_mode": "out"
        }
      },
      "interactivity": {
        "events": {
          "onhover": { "enable": true, "mode": "bubble" },
          "onclick": { "enable": true, "mode": "repulse" }
        },
        "modes": {
          "bubble": { "distance": 120, "size": 12, "duration": 2, "opacity": 0.6 },
          "repulse": { "distance": 100, "duration": 0.4 }
        }
      },
      "retina_detect": true
    });
  }
}

// 组件挂载时初始化particles
onMounted(() => {
  // 延迟初始化，确保DOM已渲染
  setTimeout(() => {
    initParticles();
  }, 100);
});

</script>


<template>
  <div id="particles-bg"></div>
  <div class="register-bg">
    <div class="register-card">
      <h2 class="register-title">注册新账号</h2>
      <div class="register-subtitle">请填写注册信息</div>
      <form @submit.prevent="regist()">
        <div class="form-group">
          <label for="usernameInput">用户名</label>
          <div class="input-wrapper">
            <span class="input-icon">👤</span>
            <input class="ipt" type="text" id="usernameInput" v-model="registUser.username" placeholder="请输入用户名" @blur="checkUsername()">
          </div>
          <span id="usernameMsg" class="msg" v-text="usernameMsg"></span>
        </div>
        <div class="form-group">
          <label for="userPwdInput">密码</label>
          <div class="input-wrapper">
            <span class="input-icon">🔒</span>
            <input class="ipt" type="password" id="userPwdInput" v-model="registUser.userPwd" placeholder="请输入密码（8-20位，包含大小写字母、数字、特殊字符）" @blur="checkUserPwd()">
          </div>
          <span id="userPwdMsg" class="msg" v-text="userPwdMsg"></span>
        </div>
        <div class="form-group">
          <label for="confirmPwdInput">确认密码</label>
          <div class="input-wrapper">
            <span class="input-icon">🔒</span>
            <input class="ipt" type="password" id="confirmPwdInput" v-model="confirmPwd" placeholder="请再次输入密码（8-20位，包含大小写字母、数字、特殊字符）" @blur="checkConfirmPwd()">
          </div>
          <span id="confirmPwdMsg" class="msg" v-text="confirmPwdMsg"></span>
        </div>
        
        <!-- 手机号输入 -->
        <div class="form-group">
          <label for="phoneInput">手机号</label>
          <div class="input-wrapper">
            <span class="input-icon">📱</span>
            <input class="ipt" type="tel" id="phoneInput" v-model="registUser.phone" placeholder="请输入手机号" @blur="checkPhone()">
          </div>
          <span id="phoneMsg" class="msg" v-text="phoneMsg"></span>
        </div>
        
        <!-- 验证码输入 -->
        <div class="form-group">
          <label for="verificationCodeInput">验证码</label>
          <div class="code-input-group">
            <div class="input-wrapper" style="flex: 1;">
              <span class="input-icon">🔐</span>
              <input class="ipt" type="text" id="verificationCodeInput" v-model="registUser.verificationCode" placeholder="请输入5位验证码" maxlength="5" @blur="checkVerificationCode()">
            </div>
            <button 
              type="button" 
              @click="generateCode"
              :disabled="!registUser.phone || generatingCode || countdown > 0"
              class="generate-code-btn"
            >
              {{ generatingCode ? '生成中...' : (countdown > 0 ? `${countdown}s` : '获取验证码') }}
            </button>
          </div>
          <span id="verificationCodeMsg" class="msg" v-text="verificationCodeMsg"></span>
          <div v-if="codeGenerated" class="code-tip">
            <i class="fa-solid fa-info-circle"></i>
            验证码已生成，请联系管理员获取
          </div>
        </div>
        
        <!-- 安全问题设置 -->
        <div class="form-group">
          <label>安全问题设置（至少选择3个）</label>
          <div class="security-questions-container">
            <div class="questions-list">
              <div 
                v-for="question in securityQuestions" 
                :key="question.id"
                class="question-item"
                :class="{ selected: selectedQuestions[question.id] }"
              >
                <input 
                  type="checkbox" 
                  :id="`question-${question.id}`"
                  :checked="selectedQuestions[question.id]"
                  @change="toggleQuestion(question.id)"
                >
                <label :for="`question-${question.id}`">{{ question.question }}</label>
              </div>
            </div>
            
            <!-- 答案输入区域 -->
            <div v-if="Object.keys(selectedQuestions).length > 0" class="answers-section">
              <h4>请为选中的问题填写答案：</h4>
              <div 
                v-for="questionId in Object.keys(selectedQuestions)" 
                :key="questionId"
                class="answer-input"
              >
                <label :for="`answer-${questionId}`">
                  {{ securityQuestions.find(q => q.id == questionId)?.question }}
                </label>
                <div class="input-wrapper">
                  <span class="input-icon">💭</span>
                  <input 
                    class="ipt" 
                    type="text" 
                    :id="`answer-${questionId}`"
                    v-model="selectedQuestions[questionId].answer" 
                    placeholder="请输入答案"
                    @blur="checkSecurityQuestions()"
                  >
                </div>
              </div>
            </div>
          </div>
          <span class="msg" v-text="securityQuestionsMsg"></span>
        </div>
        <div class="buttonContainer">
          <input class="btn1" type="submit" value="注 册">
        </div>
      </form>
      <div class="login-tip">已有账号？<router-link to="/login" class="login-link">立即登录</router-link></div>
    </div>
  </div>
</template>


<style scoped>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body, html {
    height: 100%;
    font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

#particles-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #d6e0ff 0%, #e0c3fc 100%);
    z-index: -1;
    overflow: hidden;
}

/* particles.js 会自动处理粒子样式 */
.register-bg {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
.register-card {
    background: #fff;
    border-radius: 18px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.13);
    padding: 36px 30px 24px 30px;
    min-width: 340px;
    max-width: 90vw;
    display: flex;
    flex-direction: column;
    align-items: stretch;
}
.register-title {
    text-align: center;
    color: #2d2d4b;
    font-size: 26px;
    font-weight: 700;
    margin-bottom: 6px;
}
.register-subtitle {
    text-align: center;
    color: #888;
    font-size: 15px;
    margin-bottom: 22px;
}
.form-group {
    display: flex;
    flex-direction: column;
    margin-bottom: 18px;
}
.form-group label {
    margin-bottom: 6px;
    color: #3a7ca5;
    font-size: 15px;
    font-weight: 500;
}
.input-wrapper {
    display: flex;
    align-items: center;
    background: #f7f7fb;
    border-radius: 6px;
    border: 1.5px solid #e0e0ef;
    padding: 0 10px;
    transition: border-color 0.2s;
}
.input-wrapper:focus-within {
    border-color: #b39ddb;
}
.input-icon {
    font-size: 18px;
    color: #b39ddb;
    margin-right: 6px;
}
.ipt {
    border: none;
    background: transparent;
    padding: 10px 0;
    font-size: 16px;
    outline: none;
    flex: 1;
}
.msg {
    min-height: 18px;
    font-size: 13px;
    margin-top: 3px;
    color: #e74c3c;
    transition: color 0.2s;
}
.buttonContainer {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 6px;
    margin-bottom: 10px;
}
.btn1 {
    border: none;
    border-radius: 6px;
    padding: 10px 0;
    width: 100%;
    background: linear-gradient(90deg, #b39ddb 0%, #a18cd1 100%);
    color: #fff;
    font-size: 17px;
    font-weight: 600;
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(163, 148, 255, 0.08);
    transition: background 0.2s, transform 0.1s;
    letter-spacing: 2px;
}
.btn1:hover, .btn1:focus {
    background: linear-gradient(90deg, #a18cd1 0%, #b39ddb 100%);
    transform: translateY(-2px) scale(1.03);
}
.login-tip {
    text-align: center;
    color: #888;
    font-size: 14px;
    margin-top: 8px;
}
.login-link {
    color: #b39ddb;
    text-decoration: none;
    margin-left: 2px;
    transition: color 0.2s;
}
.login-link:hover {
    color: #7e57c2;
}

/* 安全问题样式 */
.security-questions-container {
    margin-top: 10px;
}

.questions-list {
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #e0e0ef;
    border-radius: 6px;
    padding: 10px;
    background: #f9f9f9;
}

.question-item {
    display: flex;
    align-items: center;
    padding: 8px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;
    margin-bottom: 5px;
}

.question-item:hover {
    background: #f0f0f0;
}

.question-item.selected {
    background: #e8f5e8;
    border: 1px solid #4caf50;
}

.question-item input[type="checkbox"] {
    margin-right: 10px;
}

.question-item label {
    margin: 0;
    cursor: pointer;
    flex: 1;
    font-size: 14px;
}

.answers-section {
    margin-top: 15px;
    padding: 15px;
    background: #f7f7fb;
    border-radius: 6px;
    border: 1px solid #e0e0ef;
}

.answers-section h4 {
    color: #3a7ca5;
    margin-bottom: 15px;
    font-size: 16px;
}

.answer-input {
    margin-bottom: 15px;
}

.answer-input label {
    display: block;
    margin-bottom: 5px;
    color: #2d2d4b;
    font-weight: 500;
    font-size: 14px;
}

/* 验证码相关样式 */
.code-input-group {
    display: flex;
    gap: 10px;
    align-items: stretch;
}

.generate-code-btn {
    padding: 10px 15px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    white-space: nowrap;
    font-size: 14px;
    transition: background 0.2s;
    min-width: 120px;
}

.generate-code-btn:hover:not(:disabled) {
    background: #0056b3;
}

.generate-code-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.code-tip {
    margin-top: 8px;
    padding: 8px 12px;
    background: #e7f3ff;
    border: 1px solid #b3d9ff;
    border-radius: 4px;
    color: #0066cc;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 5px;
}

.code-tip i {
    color: #0066cc;
}
#particles-bg {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    width: 100vw;
    height: 100vh;
    z-index: 0;
    pointer-events: auto;
}
.register-bg, .register-card {
    position: relative;
    z-index: 1;
}
@media (max-width: 480px) {
    .register-card {
        padding: 18px 6vw 18px 6vw;
        min-width: unset;
    }
    .btn1 {
        font-size: 15px;
    }
}
</style>

